import ClientJs from './clientjs'
import {dateFormat} from './utils.js'
import Storage from '@/base/storage.js'

//底部菜单切换需要判断校园营销岗位、集客随销岗位有没有输入关联的手机号或者工号
export const needNumMixin = {
    methods:{
        checkStationTelNum(stationId,relTelnum){
            let retFlg = true;
            if(stationId == this.CONSTVAL.STATION_JKSX|| stationId ==this.CONSTVAL.STATION_SCHOOL){
                //你当前是集客随销岗位，XXX
                let msg = '';
                if(stationId == this.CONSTVAL.STATION_JKSX){
                    msg = '你当前是 <span class="alert-title">集客随销岗位</span> ，请前往【我的】输入关联的工号';
                } else {
                    msg = '你当前是 <span class="alert-title">校园营销岗位</span> ，请前往【我的】输入关联的手机号';
                }
                if(!relTelnum){
                    retFlg = false;
                    this.$messagebox({
                        title: '温馨提示',
                        message: msg,
                        showCancelButton: false
                    }).then(action =>{
                        this.$router.push('/my');
                    });
                }
            }
            return retFlg;
        }
    }
}

//获取定位信息
export const clientLocalMixin = {
    methods:{
        getClientTrueLocal(){
            ClientJs.getLocation('','getLocationInfoCb');
        },
        //获取地理位置的返回事件
        getLocationInfoCb(obj){
            let location;
            location = obj.address;//位置
            //let lat = obj.latitude;//经度
            //let lon = obj.longitude;//纬度
            Storage.set('location',obj.location || 'empty');
            Storage.set('latitude',obj.latitude || 'empty');
            Storage.set('longitude',obj.longitude || 'empty');
            //没获取到位置信息
            if(!location){
                this.$alert('未获取到位置信息，无法签到');
            } else {
                this.$store.commit('SET_LOCAL',location);
            }
        }
    },
    mounted(){
        // 将getLocationInfoCb方法绑定到window下面，提供给外部调用
        window['getLocationInfoCb'] = (result) => {
            this.getLocationInfoCb(result)
        }
    }
}

export const clientFromOutMixin = {
    data(){
        return{
            location:'月球',//定位信息
            latitude:'0.1',// 纬度
            longitude:'0.1',// 经度
            webUrl:'',
            uinfo:{}
        }
    },
    mounted(){
        // 将getLocationInfoCb方法绑定到window下面，提供给外部调用
        window['getSysInfoCB'] = (obj) => {
            this.webUrl = obj.serverUrl;
            this.location = obj.address;//位置
            this.latitude = obj.latitude;//经度
            this.longitude = obj.longitude;//纬度
            let res = obj.userInfo;
            let uinfo = JSON.parse(res);
            this.$http.defaults.headers.tokenid = uinfo.tokenid;
            
            let oldUinfo = Storage.session.get('userInfo');
            let relTelnum = oldUinfo && oldUinfo.relTelnum;//学生手机号
            if(relTelnum){
                uinfo.relTelnum = relTelnum;
            }
            this.uinfo = uinfo;
            Storage.session.set('userInfo',uinfo);
            Storage.set('webUrl',this.webUrl);
            this.doSth();
        };
        
        //获取操作员基本信息
        ClientJs.getSysInfo('getSysInfoCB');
        

    }
}


//读取身份证相关的
export const clientLanyaMixin = {
    data() {
        return {
            marketTimer:null,
            nfcFlg:false,
            isAndroid:(/android/gi).test(navigator.appVersion),
            curLanya:{id:'0',label:'请选择'},//当前选择的蓝牙设备
            readSfzFlg:false,
            nowDate:'',//当前日期
            limitDate:'',//限制年龄  16岁
            saveSfzFlg:false,
            sfzAttachId:'',//身份证附件ID
            headId:'',//身份证头像ID
            signImgs:'',//签名图片
            pseq:'',//拍照返回 证件欲占返回的
            netSrl:'',//拍照返回 提交的主键
            isScanning:false,//是否正在扫描蓝牙
            isReadingFlg:true,//是否正在读取身份证
            busiType:'',//业务类型 选号入网业务类型：enter_net，物联网卡业务：iot_enter_net
            sfzCameraImageIpdFlg:true,//没有生僻字，不需要上传拍摄的照片
            rareWordPicId:'',//有生僻字后上传拍摄的照片的附件编号
            sfzObj:{
                sfzId:'',
                sfzName:'',
                sfzAddr:'',
                usAddr:'',
                sfzStartDate:'',
                sfzEndDate:'',
                nation:'',
                sex:'',
                idCardType:'',
                idCardValidity:'',
                birthYear:'',//年
                birthMonth:'',//月
                birthDay:'',//日
                idCardOrganization:''
            },
            tmpIsPublicSrc:0,//默认为非公用（预配号）
            isRare:'0',//0 无生僻字  1 有生僻字
            sfzCameraImage:'',//拍的身份证图片
            sfzClientPath:'',//照片在手机客户端的路径
        }
    },
    methods:{
        //是否支持NFC
        isSupportNFC(){
            if((/android/gi).test(navigator.appVersion)){
                window.upload.isSupportNFC("isNFC");
            }
        },
        //调用客户端扫描匹配过的蓝牙设备
        clientScan(){
            this.isReadingFlg = true;
            this.isScanning = true;//正在扫描蓝牙设备 
            ClientJs.autoReadDevise("autoPpCallBack");
        },
        //展示所有的蓝牙设备
        showLanyaDevice(){
            this.isReadingFlg = true;
            this.readSfzagainFlg = false;
            this.clearSfzInfo();
            ClientJs.showLanyaDevice("getIdentify","isSaveCallBack",this.tmpIsPublicSrc)
        },
        //读取nfc按钮事件
        readSfzNfc(){
            this.isReadingFlg = true;
            let tmpFlg = false;
            if(this.tmpIsPublicSrc == '1'){
                tmpFlg = true;
            }
            window.upload.nfcReadIdCard("getIdentify","isSaveCallBack",tmpFlg);//,this.tmpIsPublicSrc
        },
        //点击拍照
        paizhao(uinfo,callBackFn,noticeCallBackFn){
           
            let sfzObj = this.sfzObj;
            if(!sfzObj.sfzId){//如果没有证件号，则不再继续办理
                this.$alert('身份证数据留存失败，请重新读取身份证');
                return;
            }
            let param = {
                userName:sfzObj.sfzName,//证件名
                address:sfzObj.sfzAddr,//地址
                certId:sfzObj.sfzId,//证件号
                deviceType:this.curLanya.id,//读证设备类型
                deviceName:this.curLanya.label,//读证设备名称
                phoneType:sfzObj.phoneType,//手机型号
                certeffDate:sfzObj.sfzStartDate,//生效时间
                certexpDate:sfzObj.sfzEndDate,//失效时间
                telNumber:this.telNumber,//预配号
                idCardType:sfzObj.idCardType,//证件类型
                headId:this.headId,//身份证头像流水
                staffId: uinfo.staffId,
                region: uinfo.region,
                crmId: uinfo.crmId,
                busiType:this.busiType,//业务类型 选号入网业务类型：enter_net，物联网卡业务：iot_enter_net
                servNumber: uinfo.servNumber
            }
            if(this.busiType == 'iot_enter_net'){//13位物联网卡号人证比对通过不了
                param.telNumber = '';
            }
            console.info(param);
            //noticeCallBack 立即回调 通知拍照结果
            ClientJs.openCamera(JSON.stringify(param),callBackFn||"mCallBackMethod",noticeCallBackFn||"noticeCallBack",this.tmpIsPublicSrc)
        },
        //读取身份证
        readSfz(){
            console.error(this.tmpIsPublicSrc+"====this.tmpIsPublicSrc")
            //TODO
            // let sfzResult = {
            //     retCode:'0',
            //     retMsg:'',
            //     deviceType:'100',
            //     deviceName:'华大100',
            //     readIdNo:'321029200112098827',
            //     readName:'汪精精',
            //     readAddress:'江苏省南京市建邺区嘉陵江东街18号国家广告园6栋16楼新大陆',
            //     certeffdate:'20100102',
            //     certexpdate:'20250102',
            //     idCardSex:'柯尔克孜族',
            //     idCardNation:'男',
            //     phone_type:'',
            //     idCardType:'IdCard'
            // };
            // let saveResult = {
            //     retCode:'0',
            //     retMsg:'预留身份证信息失败'
            // };

            // setTimeout(function(){getIdentify(JSON.stringify(sfzResult))},2000);
            // setTimeout(function(){isSaveCallBack(JSON.stringify(saveResult))},4000);
            // return;
            this.isReadingFlg = true;
            if(this.curLanya.id == "5"){//当前连接的是手机NFC
                let tmpFlg = false;
                if(this.tmpIsPublicSrc == '1'){
                    tmpFlg = true;
                }
                window.upload.nfcReadIdCard("getIdentify","isSaveCallBack",tmpFlg);
            } else {
                //蓝牙设备读取
                ClientJs.readIdCard("getIdentify","isSaveCallBack",this.tmpIsPublicSrc);
            }
        },
        //add by qhuang 20190620 身份证上有生僻字，需要拍下身份证照片
        openCameraAndShow(){
            ClientJs.openCameraAndShow("1","getSfzCameraPicCb")
        },
        clearSfzInfo(){
            let sfzObj = this.sfzObj;
            sfzObj.sfzId = '';//读取到的证件号
            sfzObj.sfzName = '';//读取到的名字
            sfzObj.sfzAddr = '';//读取到的地址
            sfzObj.usAddr = '';//用户常住地址默认为身份证地址
            sfzObj.sfzStartDate = '';//身份证有效期begin
            sfzObj.sfzEndDate = '';//身份证有效期end
            sfzObj.phoneType = '';
            sfzObj.nation = '';
            sfzObj.sex = '';
            sfzObj.idCardType = '';
            sfzObj.idCardValidity = '';
            sfzObj.idCardOrganization = '';
            sfzObj.birthYear = '';//年
            sfzObj.birthMonth = '';//月
            sfzObj.birthDay = '';//日
            sfzObj.passNumber = '';//港澳台参数
            sfzObj.issuesNums = '';//港澳台参数
            this.saveSfzFlg = false;
        },
        //签名
        sign(){
            ClientJs.qianming('signCallBack');
        }
    },
    mounted(){
        this.nowDate = dateFormat(new Date(),'yyyyMMdd');
        let now = new Date();
        let year = now.getFullYear() - 16;
        this.limitDate = dateFormat(new Date(year,now.getMonth(),now.getDate()),'yyyyMMdd');
        // 将isNFC方法绑定到window下面，提供给外部调用
        window['isNFC'] = (result) => {
            let info = JSON.parse(result);
            if(info.retCode =='0'){
                this.nfcFlg = true;
            }
        };
        //客户端自动匹配设备并匹配后的回调函数
        window['autoPpCallBack'] = (result) => {
            let info = JSON.parse(result);
            console.info(info);
            var retCode = info.retCode;
            var retMsg = info.retMsg;
            var status = info.status;
            if(retCode == "0"){//获取成功
                if(status == "0"){//未匹配
                    this.curLanya = {id:'0',label:'未选择'};
                    this.$toast(retMsg);////提示未发现匹配的设备
                    this.isReadingFlg = false;
                }else if(status == "1"){ //匹配成功
                    var deviceType = info.deviceType;//设备类型 1:惠泉 2：亿数3：华大 4:神思
                    var deviceName = info.deviceName;//设备类型名称 1:惠泉 2：亿数3：华大 4:神思
                    this.curLanya = {id:deviceType,label:deviceName};//初始化为之前匹配过的蓝牙设备
                    this.isReadingFlg = true;
                    ClientJs.readIdCard("getIdentify","isSaveCallBack",this.tmpIsPublicSrc);
                }
            }else{
                this.$toast(retMsg);
                this.isReadingFlg = false;
            }
            this.isScanning = false;//扫描蓝牙设备结束
        };
        //拍照回调
        window['noticeCallBack'] = () => {
            console.info('====noticeCallBack=====');
            this.paizhaoStep = 'facevalidate';
        };
        //拍照后客户端回调人证比对结果
        window['mCallBackMethod'] = (result) => {
            console.info('==mCallBackMethod==')
            console.info(result);
            try {
                //把客户端返回的解析流
                let info = JSON.parse(result);
                console.info(info);
                this.currentStep = 'step2';//H5页面跳到展示身份证信息那页
                if(info.retCode == '0'){//人像比对成功
                    this.pseq = info.data.pseq;
                    this.netSrl = info.data.netSrl;
                    this.checkSucess();
                } else {
                    this.paizhaoStep = '';
                    this.currentStep = 'step1';
                    this.getSfzImgFlg = false;
                    this.$alert(info.retMsg||'人像比对失败');
                }  
            } catch (error) {
                this.$alert('人像比对返回报文解析失败：' + result);
            }
            
            
        };
        //读取身份证回调
        window['getIdentify'] = (result) => {
            this.isReadingFlg = false;
            this.closeLoading();
            var info = result.replace(new RegExp('\n', 'g'),'\\n');
            try{
                info = JSON.parse(info);
            }catch(err){
                try{
                    info= eval("("+info+")");
                }catch(err2){
                    this.$alert('身份证信息读取异常，请更换设备');
                    return false;
                }
            }
            var retCode = info.retCode;
            var retMsg = info.retMsg;
            this.curLanya = {id:info.deviceType,label:info.deviceName};
            if(retCode == "0"){//获取成功
                let sfzObj = this.sfzObj;
                this.readSfzFlg = true;
                this.readSfzagainFlg = false;//暂时不能重新读取身份证
                sfzObj.sfzId = info.readIdNo.replace(/(^\s*)|(\s*$)/g, "");//读取到的证件号
                sfzObj.sfzName = info.readName.replace(/(^\s*)|(\s*$)/g, "");//读取到的名字
                sfzObj.sfzAddr = info.readAddress.replace(/(^\s*)|(\s*$)/g, "");//读取到的地址
                sfzObj.usAddr = info.readAddress.replace(/(^\s*)|(\s*$)/g, "");//用户常住地址默认为身份证地址
                sfzObj.sfzStartDate = info.certeffdate;//身份证有效期begin
                sfzObj.sfzEndDate = info.certexpdate.replace(/\s/g,'');//身份证有效期end
                if(sfzObj.sfzEndDate == '长期'){//如果是长期处理成20991231
                    sfzObj.sfzEndDate = '20991231'
                }
                sfzObj.sex = info.idCardSex.replace(/(^\s*)|(\s*$)/g, "");//读取到的性别
                sfzObj.nation = info.idCardNation.replace(/(^\s*)|(\s*$)/g, "");//读取到的民族
                sfzObj.phoneType = info.phone_type;
                sfzObj.idCardType = info.idCardType || 'IdCard';//证件类型
                sfzObj.idCardValidity = info.idCardValidity;//有效期
                sfzObj.idCardOrganization = info.idCardOrganization;//签发机关
                sfzObj.birthYear = info.idCardBirth_Year;//年
                sfzObj.birthMonth = info.idCardBirth_Month;//月
                sfzObj.birthDay = info.idCardBirth_Day;//日
                let idCardType = sfzObj.idCardType;//证件类型
                if(idCardType == 'IdCardTW' || idCardType == 'IdCardGA'){//台湾居住证 港澳居住证
                    sfzObj.passNumber = info.passNumber;
                    sfzObj.issuesNums = info.issuesNums;
                }

                //判断16岁限制入网
                let idcardStr = sfzObj.sfzId;
				if(idcardStr && idcardStr.length > 14){
                    let userDate = idcardStr.substr(6,8);
				    if(userDate > this.limitDate){
                        this.readSfzagainFlg = true;
                        this.readSfzFlg = false;
						this.$alert('用户出生日期：'+userDate+'，16岁以下用户限制入网！');
				    }
                }
               //判断身份证是否失效 
               let certexpdate_card = info.certexpdate.trim();//身份证失效时间
                if(certexpdate_card && !isNaN(certexpdate_card)){
                    if(certexpdate_card < this.nowDate){
                        this.readSfzFlg = false;
                        this.readSfzagainFlg = true;
                        this.$alert('该用户身份证已失效，身份证有效期结束时间为：'+certexpdate_card);
                    }
                }
            }else{
                this.readSfzFlg = false;
                this.clearSfzInfo();
                this.$toast(retMsg);
            }
            //该蓝牙设备去服务端校验是否在黑名单里
            this.deviceBlackByBusi();
        };
        //读完身份证后是否在服务端预留成功
        window['isSaveCallBack'] = (result) => {
            console.info('------isSaveCallBack------')
            let info = JSON.parse(result);
            console.info(info);
            this.saveSfzFlg = false;
            this.readSfzagainFlg = true;
            if (info.retCode == '0'){
                this.saveSfzFlg = true;
                this.headId = info.headId;
                this.sfzAttachId = info.cardPicId;
                this.isRare = info.isRare || '0';//0 无生僻字  1 有生僻字 2 59个民族外的少数民族 3：生僻字加少数民族

                if(this.isRare != '0'){
                    this.sfzCameraImageIpdFlg = false;//需要上传照片
                    this.sfzCameraImage = '';
                } else {
                    this.sfzCameraImageIpdFlg = true;
                }
                //非预配号 没有营销案校验
                if(this.tmpIsPublicSrc){
                    this.paizhaoStep = '';
                } else {
                    if(!this.marketResultFlg){
                        this.paizhaoStep = 'validate';//等待营销案校验结果
                        this.marketTimer = setInterval(function (){
                            if(this.marketResultFlg){
                                this.paizhaoStep = '';
                                clearInterval(this.marketTimer);
                            }
                        }.bind(this),100)
                        
                    }else{
                        this.paizhaoStep = '';
                    }
                }
            } else {
                this.readSfzFlg = false;
                this.showPaiZhao = false;
                this.$alert(info.retMsg||'上传身份证信息失败');
            }
        },
        window['signCallBack'] = (info) => {          
            if(info.retCode=='0'){ 
                this.signImgs = info.retImg;
                this.$refs.signDom.src = 'data:image/jpeg;base64,' + this.signImgs;
                console.info(this.checkInstallInfo());
                if(this.checkInstallInfo()){//有赠卡校验
                    this.submitStep = 'initTj';
                } else {
                    this.submitStep = '';
                }
            }
        },
        //拍完身份证照片后的回调
        window['getSfzCameraPicCb'] = (info) => {
            console.info(info);
            this.sfzCameraImage = info.fileImage;//照片的base64串
            this.sfzClientPath = info.filePath;//照片在手机客户端的路径
            this.$refs.sfzImg.src = 'data:image/jpeg;base64,' + info.fileImage;
            if(info.fileImage){
                let param = {
                    basePic:info.fileImage,
                    cardId:this.sfzObj.sfzId,
                    unEncrpt:true
                }
                //请求服务端上传
                let uploadURL = '/xsb/ability/rareWordUpLoad/h5upLoadImg';
                this.$http.post(uploadURL,param).then(res => {
                    console.info(res);
                    let {retCode,retMsg,data} = res.data;
                    if(retCode != '0'){
                        this.sfzCameraImageIpdFlg = false;
                        this.$alert(retMsg || '上传照片异常')
                    } else {
                        this.rareWordPicId = data.rareWordPicId;
                        this.sfzCameraImageIpdFlg = true;
                    }
                })
            }
        }
    }
}